/*eslint-disable */
import storageApi from '../../core/storage/storage';

@Inject('$log', '$rootScope', '$state', '$filter', 'previewTableService', 'ngDialogService')
class PreviewTableController {
  constructor() {
    this.name = $state.params.name;
    this.id = $state.params.id;
    this.boxId = $state.params.boxId;
    this.ids = [];
    this.params = {
      orgId: $rootScope.orgId || storageApi.get('orgId'),
      creatorId: $rootScope.userId || storageApi.get('userId'),
      templateId: this.id,
      templateType: this.boxId,
      deleted: 0,
    }
    // 获取模板图片
    this.$getTemplate(this.id);
    // 获取历史记录
    this.$getHistoryRecord(this.params);
  }

  $getTemplate(tableId) {
    this.previewTableService
      .get({ id: tableId })
      .then((res) => {
        this.previewInfo = res.data;
      });
  }

  $getHistoryRecord(params) {
    this.previewTableService
      .query({ mapParams: params })
      .then((res) => {
        this.historyRecord = this.$handleData(res.rows);
      });
  }

  $handleData(list) {
    let dateList = [];
    list.forEach((item) => {
      item.date = this.$handleDate(this.$filter('date')(item.createdTime, 'yyyy-M-dd'));
      if (dateList.indexOf(item.date) === -1) {
        dateList.push(item.date);
      }
    });

    let newList = [];
    dateList.forEach((date) => {
      let obj = {
        date: date,
        list: [],
      };
      list.forEach((item) => {
        if (date === item.date) {
          obj.list.push(item);
        }
      });
      newList.push(obj);
    });
   return newList;
  }

  $handleDate(time) {
    var show_day = new Array('星期一','星期二','星期三','星期四','星期五','星期六','星期日');
    var day = new Date(time).getDay();
    var current = this.$filter('date')(new Date(), 'yyyy-M-dd');
    if (time) {
      var date = time.split('-')[0] + '年' + time.split('-')[1] + '月' + time.split('-')[2] + '日' + show_day[day-1];
    }
    if (time == current) {
      this.isShowToday = true;
    } else {
      this.isShowToday = false;
    }
    return date;
  }

  $delete(value, item, index) {
    this.previewTableService
      .delete([value.id])
      .then((res) => {
        if (res.success) {
          item.list.splice(index, 1);
        }
      });
  }

  $clearAll() {
    this.historyRecord.forEach((param) => {
      param.list.forEach((item) => {
        this.ids.push(item.id);
      });
    });
    this.ngDialogService.confirm('确定删除此数据吗？', this.ids)
      .then((data) => {
        this.previewTableService
          .delete(this.ids)
          .then((res) => {
            if (res.success) {
              this.ngDialogService.alertSuccess(res.message);
              this.$getHistoryRecord(this.params);
            }
          });
      });
  }

  getTemplateSrc() {
    if (this.previewInfo && this.previewInfo.previewImgId) {
      const src = `/${this.previewInfo.fileBean.filePath}`;
      return src;
    }
  }
}

export default PreviewTableController;
